﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WAD.BLL;
using WAD.DAL;

namespace WAD.Client2.WXPay
{
    /// <summary>
    /// 支付结果通知回调处理类（微街秀的异步通知，调用此类）
    /// 负责接收微信支付后台发送的支付结果并对订单有效性进行验证，将验证结果反馈给微信支付后台
    /// </summary>
    public class ResultNotify : Notify
    {
        public ResultNotify(Page page) : base(page) { }

        public override void ProcessNotify()
        {
            WxPayData notifyData = GetNotifyData(); //获取通知参数

            //检查支付结果中transaction_id是否存在
            if (!notifyData.IsSet("transaction_id"))
            {
                //若transaction_id不存在，则立即返回结果给微信支付后台
                WxPayData res = new WxPayData();
                res.SetValue("return_code", "FAIL");
                res.SetValue("return_msg", "支付结果中微信订单号不存在");
                Log.Error(this.GetType().ToString(), "The Pay result is error : " + res.ToXml());
                page.Response.Write(res.ToXml());
                page.Response.End();
            }

            string transaction_id = notifyData.GetValue("transaction_id").ToString();   //微信订单号
            string order_no = notifyData.GetValue("out_trade_no").ToString();       //微街秀订单号
            string total_fee = notifyData.GetValue("total_fee").ToString();             //订单总金额 单位：分
            string notify_time = notifyData.GetValue("time_end").ToString();           //微信通知时间 格式为 yyyyMMddHHmmss
            string buyer_email = "";

            //查询订单，判断订单真实性
            if (!QueryOrder(transaction_id))
            {
                //若订单查询失败，则立即返回结果给微信支付后台
                WxPayData res = new WxPayData();
                res.SetValue("return_code", "FAIL");
                res.SetValue("return_msg", "订单查询失败");
                Log.Error(this.GetType().ToString(), "Order query failure : " + res.ToXml());
                page.Response.Write(res.ToXml());
                page.Response.End();
            }
            //查询订单成功
            else
            {
                WxPayData res = new WxPayData();
                res.SetValue("return_code", "SUCCESS");
                res.SetValue("return_msg", "OK");
                Log.Info(this.GetType().ToString(), "order query success : " + res.ToXml());

                //微街秀业务处理
                CallBack(transaction_id, order_no, total_fee, notify_time, buyer_email);

                page.Response.Write(res.ToXml());
                page.Response.End();
            }
        }

        //查询订单
        private bool QueryOrder(string transaction_id)
        {
            WxPayData req = new WxPayData();
            req.SetValue("transaction_id", transaction_id);
            WxPayData res = WxPayApi.OrderQuery(req);
            if (res.GetValue("return_code").ToString() == "SUCCESS" &&
                res.GetValue("result_code").ToString() == "SUCCESS")
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        #region 微街秀业务处理

        public void CallBack(string trade_no, string order_no, string total_fee, string notify_time, string buyer_email)
        {
            notify_time = FormatTime(notify_time);
            double money = Convert.ToDouble(total_fee) * 0.01;  //单位转换为 “元”
            string errMsg = FCOrderBLL.Pay_CallBack(order_no, money.ToString(), notify_time, page.Request.UserHostAddress, GetMsg(trade_no, order_no, buyer_email, total_fee, page.Request.UserHostAddress), WAD.WEB.AppCode.WJXConfig.EncryptConfig.DES_KEY);
            if (errMsg.Length > 0)
            {
                errMsg = string.Format("订单处理失败【{0}: 订单号:{1},回调时间:{2}】", errMsg, order_no, DateTime.Now);
                DaoLogcat.Add("pay", errMsg);   //订单处理失败，添加错误日志
            }
        }

        string GetMsg(string trade_no, string order_no, string buyer_email, string total_fee, string IP)
        {
            return "{\"trade_no\":\"" + trade_no + "\",\"order_no\":\"" + order_no + "\",\"buyer_email\":\"" + buyer_email + "\",\"total_fee\":\"" + total_fee + "\",\"IP\":\"" + IP + "\"}";
        }

        //格式化日期(格式：yyyy-MM-dd HH:mm:ss) 
        string FormatTime(string str)
        {
            //2015-01-01 12:59:59
            return str.Insert(4, "-").Insert(7, "-").Insert(10, " ").Insert(13, ":").Insert(16, ":");
        }
        #endregion
    }
}